import { IText, IShape, Point, DrawMode } from './../model';
import { BoundingBox } from './../base';
import { PointUtil } from './../utils';

export class TextShape extends BoundingBox implements IShape {

    type: DrawMode;
    x: number;
    y: number;
    text: string;
    maxWidth?: number;
    height = 16;
    fillStyle: string;
    font = '12px Arial';
    textBaseline: CanvasTextBaseline = 'top';


    constructor(options: IText) {
        super();
        this.type = options.type;
        this.x = options.x;
        this.y = options.y;
        this.text = options.text;
        this.maxWidth = options.maxWidth;
        this.fillStyle = options.fillStyle || '#000';
    }

    update() {

    }

    render(ctx: CanvasRenderingContext2D) {
        ctx.save();
        ctx.font = this.font;
        ctx.fillStyle = this.fillStyle;
        ctx.textBaseline = this.textBaseline;
        ctx.beginPath();
        this.type === 'stroke' ? ctx.strokeText(this.text, this.x, this.y, this.maxWidth)
            : ctx.fillText(this.text, this.x, this.y, this.maxWidth);
        ctx.restore();
    }

    checkClick(ctx: CanvasRenderingContext2D, point: Point): boolean {
        this.controlRect = this.getControlRect(ctx);
        const checkResult = this.getPointIsInsideArea(point);
        if (checkResult) {
            this.drawBorder(ctx);
            this.drawControls(ctx);
        }
        return checkResult;
    }

    getControlRect(ctx: CanvasRenderingContext2D) {
        const textMetric = ctx.measureText(this.text);
        const width = textMetric.actualBoundingBoxRight + textMetric.actualBoundingBoxLeft;
        const height = textMetric.actualBoundingBoxAscent + textMetric.actualBoundingBoxDescent;
        this.controlRect = {
            x: this.x,
            y: this.y,
            width,
            height
        };
        return this.controlRect;
    }

    getPointIsInsideArea(point: Point) {
        const { x, y, height, width } = this.controlRect;
        return point.x > x && point.y > y && point.x < (x + width) && point.y < (y + height);
    }
}


